# -*- encoding:utf8 -*-

from django.dispatch import receiver
from attendance.leave import leave_app_switch_approved
from attendance.models import LeaveApplication
from attendance.convert import str2dt,date2str,str2date
from recordproc import record
from reportproc import report
from attendance.date_func import month_finalday
from datetime import timedelta

@receiver(leave_app_switch_approved,sender=LeaveApplication,dispatch_uid="wn_switch_approved")
def wn_switch_approved(sender,instance,**kw):
    """当假期申请状态变化时，刷新当天考勤，刷新当月统计
    """
    # datelist=set()
    
    # [ToDo]  改进LeaveApplication涉及日期
    # 这里获取leaveApplication的日期是通过其开始，结束日期，以及 对应的leaveModel日期
    # 这里会产生bug，考虑以后，直接用函数来计算需要刷新的日期    
    # datelist.add( date2str( str2dt(instance.start_time).date()) )
    # datelist.add( date2str( str2dt(instance.end_time).date()) )

    # for usedleave in instance.usedleave.all():
        # datestr=date2str( str2dt( usedleave.start_time).date() )
        # datelist.add(datestr)
    datelist=_application_related_day(instance)
    for date in datelist:
        record(instance.staff, date)
    
    # 根据月份最后一天，刷新统计
    monthlist=set()
    for dt in datelist:
        final = month_finalday(dt)
        monthlist.add(final)
    for monthfinalday in monthlist:
        report(instance.staff,monthfinalday)    
    

def _application_related_day(application):
    dateset=set()
    start_date=str2dt(application.start_time).date()
    end_date=str2dt(application.end_time).date()
    pos=start_date
    while pos<=end_date:
        dateset.add(pos)
        pos+=timedelta(days=1)
    ls=list(dateset)
    ls.sort()
    return ls